import * as CryptoJS from 'crypto-js';
const REG_CARD = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;
const Helper = {
    /**
     * 判断空值
     * @param value
     * @returns {boolean}
     */
    empty: function (value) {
        if (value === null || value === undefined || value === 'undefined' || value === '' || value === 'null') {
            return true;
        }
        return false;
    },

    /**
     * 判断空json
     * @param value
     * @returns {boolean}
     */
    emptyJson: function (value) {
        if (Helper.empty(value)) {
            return true;
        }

        for (let key in value) {
            return false;
        }

        return true;
    },

    /**
     * 判断空数组
     * @param value
     * @returns {boolean}
     */
    emptyArray(value) {
        return !Array.isArray(value) || value.length === 0;
    },

    /**
     * 去除json中null的值
     * @param value
     * @returns {{}}
     */
    clearEmpty(value) {
        if (Helper.empty(value)) {
            return {};
        }

        let result = {};
        for (let v in value) {
            let data = value[v];
            if (Helper.empty(data)) {
                continue;
            }

            if (typeof v == 'object') {
                result[v] = Helper.clearEmpty(data);
                continue;
            }

            result[v] = data;
        }

        return result;
    },

    /**
     * 获取json中的值 getValueByJsn({a: {b: 1}}, 'a', 'b')
     * @param obj
     * @param params
     * @returns {string|*|string}
     */
    getValueByJson(obj, ...params) {
        if (!obj || !params) {
            return '';
        }

        let len = params.length;
        let value = obj;
        for (let i = 0; i < len; i++) {
            let param = params[i];
            if (!param) {
                return '';
            }

            value = value[param];
            if (!value) {
                return '';
            }

            if (i < len - 1) {
                if (typeof value !== 'object') {
                    return '';
                }
            }
        }

        return value ? value : '';
    },

    /**
     * 获取区间范围内的随机值
     * @param min
     * @param max
     * @returns {*}
     */
    getRandom(min, max) {
        return Math.floor(Math.random() * (max - min)) + min
    },

    /**
     * 随机生成n位字符串
     * @param len
     * @returns {string}
     */
    genRandomStr(len) {
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        var maxPos = $chars.length;
        var randomStr = '';

        for (let i = 0; i < len; i++) {
            randomStr += $chars.charAt(Math.floor(Math.random() * maxPos));
        }

        return randomStr;
    },

    /**
     * 数组转map
     * @param items
     * @param key
     * @param value
     * @returns {{}}
     */
    array2Map(items, key, value) {
        let map = {};
        if (Array.isArray(items)) {
            for (let i = 0; i < items.length; i++) {
                let keyField = items[i][key];
                if (!Helper.empty(keyField)) {
                    map[keyField] = items[i][value];
                }
            }
        }

        return map;
    },

    /**
     * 获取数组对象中的key值
     * @param arr
     * @param key
     * @returns {*[]}
     */
    getArrayByKey(arr, key = 'id') {
        let res = [];
        if (Helper.emptyArray(arr) || Helper.empty(key)) {
            return res;
        }

        arr.forEach(item => {
            if (!Helper.empty(item[key])) {
                res.push(item[key])
            }
        })

        return res;
    },

    /**
     * 合并json
     * @param source
     * @param target
     */
    mergeJson(source, target) {
        if (Helper.empty(target)) {
            return;
        }
        if (Helper.empty(source)) {
            source = target;
            return;
        }
        for (let attr in target) {
            let targetValue = target[attr];
            let sourceValue = source[attr];

            if (Helper.empty(sourceValue)) {
                source[attr] = targetValue;
                continue;
            }

            if (Array.isArray(targetValue)) {
                if (Helper.emptyArray(targetValue)) {
                    targetValue = [];
                }
                source[attr] = targetValue;
                continue;
            }

            if (typeof targetValue === 'object') {
                Helper.mergeJson(sourceValue, targetValue)
                continue;
            }

            source[attr] = targetValue;
        }
    },

    formatFileSize(size, pointLength, units) {
        let unit;
        units = units || ['B', 'K', 'M', 'G'];
        while ((unit = units.shift()) && size > 1024) {
            size = size / 1024;
        }
        return (unit === 'B' ? size : size.toFixed(pointLength === undefined ? 2 : pointLength)) + unit;
    },

    formatAddress(address) {
        if (Helper.emptyJson(address)) {
            return "";
        }
        return Helper.formatStr("{0}{1}{2}{3}", address.provinceName, address.cityName, address.areaName, address.info);
    },

    formatStr(str, ...arg) {
        if (arguments.length > 1) {
            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "g");
                str = str.replace(reg, "##_" + i + "_##");
            }

            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("##_" + i + "_##", "g");
                let v = arguments[i + 1];
                if (Helper.empty(v)) {
                    v = "";
                }
                str = str.replace(reg, v);
            }
        }
        return str;
    },

    getBeforeDay(days) {
        const now = new Date();
        return new Date(now.getTime() - (days * 24 * 60 * 60 * 1000)); // 7天前的开始时间
    },

    getLastMonth() {
        // 获取当前日期
        const now = new Date();
        // 获取本月的第一天
        const startOfMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1).getTime();
        // 获取下月的第一天，然后减去一毫秒得到本月的最后一秒
        const endOfMonth = new Date(now.getFullYear(), now.getMonth(), 1) - 1;
        return {start: new Date(startOfMonth), end: new Date(endOfMonth)};
    },

    getCurMonth() {
        // 获取当前日期
        const now = new Date();
        // 获取本月的第一天
        const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
        // 获取下月的第一天，然后减去一毫秒得到本月的最后一秒
        const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1) - 1;
        return {start: new Date(startOfMonth), end: new Date(endOfMonth)};
    },

    /**
     * @param type 1 近7天 2 近30天 3 上月 4 本月
     */
    formatQueryDate(type) {
        let start = new Date();
        let end = new Date();
        if(type == 1){
            start = this.getBeforeDay(7);
        } else if(type == 2) {
            start = this.getBeforeDay(30);
        } else if(type == 3) {
            let data = this.getLastMonth();
            console.log(data);
            start = data.start;
            end = data.end;
        } else if(type == 4) {
            let data = this.getCurMonth();
            start = data.start;
            end = data.end;
        }else {
            return {};
        }

        return {start: this.formatDate(start, 'yyyy-MM-dd'), end: this.formatDate(end, 'yyyy-MM-dd')}
    },

    formatDate(date, format) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        let day = date.getDate();
        if (day < 10) {
            day = "0" + day;
        }

        if(format == 'yyyy-MM-dd') {
            return Helper.formatStr("{0}-{1}-{2}", year, month, day)
        } else {

            let hour = date.getHours()
            if (hour < 10) {
                hour = "0" + hour;
            }
            let minute = date.getMinutes()
            if (minute < 10) {
                minute = "0" + minute;
            }
            let second = date.getSeconds()
            if (second < 10) {
                second = "0" + second;
            }

            return Helper.formatStr("{0}-{1}-{2} {3}:{4}:{5}", year, month, day, hour, minute, second)
        }
    },

    navigateBack(isReload = false, delta = 1) {
        uni.navigateBack({
            delta: delta,
            success: () => {
                if (isReload) {
                    let pages = getCurrentPages(); //跳转页面成功之后
                    let page = null;
                    let platform = uni.getSystemInfoSync().platform;
                    if (platform == 'android') {
                        delta = delta + 1;
                    }
                    for (let i = 0; i < delta; i++) {
                        page = pages.pop();
                    }
                    if (!page) return;
                    let options = page.options;
                    console.log(options, 'options');
                    page.onLoad(options);
                }
            },
            complete: () => {
                return this.getCurrentPage();
            }
        });

    },

    getCurrentPage() {
        let routes = getCurrentPages();
        let curRoute = routes[routes.length - 1].route;
        let options = routes[routes.length - 1].options;

        let params = [];
        if(! Helper.emptyJson(options)) {
            for (let p in options) {
                params.push(p + "=" + options[p]);
            }

            if(! Helper.emptyArray(params)) {
                curRoute += "?" + params.join("&")
            }
        }

        return curRoute;
    },

    formatDistance(m) {
        let v;
        if (typeof m === 'number' && !isNaN(m)) {
            if (m >= 1000) {
                v = (m / 1000).toFixed(2) + 'km'
            } else {
                v = m + 'm'
            }
        } else {
            v = '0m'
        }
        return v;
    },

    calculateAge(birthDate) {
        let today = new Date(); // 获取今天的日期对象
        let birthYear = birthDate.getFullYear(); // 提取出生日期中的年份

        if (today.getMonth() < birthDate.getMonth()) {
            return today.getFullYear() - birthYear; // 如果当月小于出生月份，则直接返回年数差值
        } else if (today.getMonth() === birthDate.getMonth() && today.getDay() < birthDate.getDay()) {
            return today.getFullYear() - birthYear; // 如果当月等于出生月份并且当天小于出生日期，则也直接返回年数差值
        } else {
            return today.getFullYear() - birthYear + 1; // 否则加上1表示已经过了完整的一年
        }
    },

    checkCard(value) {
        // 前17位每项的系数
        let coefficient = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 除11取余的结果对应的校验位（最后一位）的值
        let checkDigitMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        let idCardReg = REG_CARD;
        if (!idCardReg.test(value)) {
            return false;
        }

        if (value.length == 18) {
            let sum = 0;
            for (let i = 0; i < 17; i++) {
                sum += value[i] * coefficient[i];
            }
            let last = checkDigitMap[sum % 11];
            if (value[17] != last) {
                return false;
            }
        }

        return true;
    },

    /**
     *加密处理
     */
    encryption(src, keyWord) {
        const key = CryptoJS.enc.Utf8.parse(keyWord);
        // 加密
        var encrypted = CryptoJS.AES.encrypt(src, key, {
            iv: key,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.NoPadding,
        });
        return encrypted.toString();
    },

    /**
     *  解密
     * @param {*} params 参数列表
     * @returns 明文
     */
    decryption(src, keyWord) {
        const key = CryptoJS.enc.Utf8.parse(keyWord);
        // 解密逻辑
        var decryptd = CryptoJS.AES.decrypt(src, key, {
            iv: key,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.NoPadding,
        });

        return decryptd.toString(CryptoJS.enc.Utf8);
    }
}

export default Helper;
